import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'

import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl/login';
import router from '@/router';
import _ from 'lodash';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

const findUserAsyncRoutes = (allAsyncRoutes: any, routes: any) => {
  //过滤出用户需要动态添加的异步路由
  return allAsyncRoutes.filter((item: any) => {
    //item:过滤一级路由
    if (routes.indexOf(item.name) != -1) {
      //接着过滤二级、三级、四级、N路由
      //代表子路由
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoutes(item.children, routes);
      }
      return true;
    }
  })
}
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttonsList:[]

  }),

  actions: {
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password });
        this.token = result.token;
        //持久化存储数据token
        setToken(result.token);
        return 'ok'
      } catch (error) {
        return Promise.reject('失败');
      }
    },

    async getInfo() {
      try {
        let result = await reqUserInfo();
        //获取用户信息:头像、名字
        this.name = result.name;
        this.avatar = result.avatar;
        this.buttonsList = result.buttons;
        //先计算出当前用户需要展示的异步路由:定义异步路由与服务器返回的数据routes进行对比
        let userRegisterAsyncRoute = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes), result.routes);
        //调用方法：动态添加用户注异步路由 + 任意路由
        this.setRoute([...userRegisterAsyncRoute, anyRoute]);
        //修改仓库里面menuRoutes的属性值
        this.menuRoutes = [...staticRoutes, ...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error);
      }
    },

    //动态添加路由
    setRoute(registerRoute: any) {
      //用户A:B:C：最终需要动态追加的路由
      registerRoute.forEach((item: any) => {
        router.addRoute(item);
      })
    }
    ,

    async reset() {
      try {
        //退出登录请求
        await reqLogOut();
        //删除本地存储的token
        removeToken();
        //情况仓库自身的关于用户信息的数据
        this.token = ''
        this.name = ''
        this.avatar = ''
        this.resetRoute();
        return 'ok';
      } catch (error) {
        return Promise.reject(error);
      }
    },
    resetRoute() {
      //当前用户退出登录，应该清空掉全部异步路由
      //获取当前用户全部路由信息
      let allRoutes = router.getRoutes();
      //用户退出登录:全部的路由清除
      allRoutes.forEach((item: any) => {
        //全部删除路由
        router.removeRoute(item.name);
      });
      //常量路由:动态添加上
      staticRoutes.forEach((item: any) => {
        router.addRoute(item);
      });
    }
  },
});
